package com.wchc.order.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wchc.config.redis.RedisService;
import com.wchc.order.Order;
import com.wchc.order.OrderActionState;
import com.wchc.order.OrderState;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListener {

    @Resource
    private RedisService redisService;

    @OnTransition(source = "ORDER_WAIT_PAY",target = "ORDER_WAIT_SEND")
    public Boolean payToSend(Message<OrderActionState> message){

        Order order = (Order) message.getHeaders().get("order");

        if(!order.getOrderState().equals(OrderState.ORDER_WAIT_PAY)){
            throw new UnsupportedOperationException("state error");
        }

        order.setOrderState(OrderState.ORDER_WAIT_SEND);
        redisService.set(order.getOrderId(), JSON.toJSONString(order));
        return true;
    }


    @OnTransition(source = "ORDER_WAIT_SEND",target = "ORDER_WAIT_RECEIVE")
    public Boolean sendToReceive(Message<OrderActionState> message){

        Order order = (Order) message.getHeaders().get("order");

        if(!order.getOrderState().equals(OrderState.ORDER_WAIT_SEND)){
            throw new UnsupportedOperationException("state error");
        }

        order.setOrderState(OrderState.ORDER_WAIT_RECEIVE);
        redisService.set(order.getOrderId(), JSON.toJSONString(order));
        return true;
    }

    @OnTransition(source = "ORDER_WAIT_RECEIVE",target = "ORDER_FINISH")
    public Boolean finishOrder(Message<OrderActionState> message){

        Order order = (Order) message.getHeaders().get("order");

        if(!order.getOrderState().equals(OrderState.ORDER_WAIT_RECEIVE)){
            throw new UnsupportedOperationException("state error");
        }

        order.setOrderState(OrderState.ORDER_FINISH);
        redisService.del(order.getOrderId());
        return true;
    }
}
